<?php

class modConversation extends model
{
	private $foundID = null;
	private $foundArgs;
	
	// Get the ID of a conversation with certain participants
	public function getConversation($m, $participants, $channel)
	{
		$args = array($participants, $channel);
		
		if ($args == $this->foundArgs)
			return $this->foundID;
		else
		{
			// We can't have less than 2 persons in the conversation.
			if (count($participants) < 2)
				return false;
				
			// Get participants model
			$pM = $m->getModel('participants');
			
			// Set the args for 'caching'.
			$args = array($participants, $channel);
			
			// Select conversations that might have the 'thing'.
			$sConversations = $this->query("SELECT id FROM conversations WHERE isChannel = '" . $channel . "' AND persons = '" . count($participants) . "'") or $this->doAjaxError();
			
			// Go through them all
			while ($fConversation = $this->fetch($sConversations))
				if ($pM->hasParticipants($fConversation['id'], $participants))
				{
					// Cache the stuff for later (re)use.
					$this->foundID   = $fConversation['id'];
					$this->foundArgs = $args;
					
					// Found
					return $fConversaton['id'];
					
				} // end if
			
			return false;
			
		} // end else
		
	} // end function
	
	// Create a new converstation
	public function newConversation($m, $participants, $channel)
	{
		$persons = count($participants);
		
		if ($persons < 2)
			return false;
		
		// Insert the conversation
		$this->query("INSERT INTO conversations (`persons`,`time`,`messages`,`isChannel`) VALUES ('" . $persons . "', '". time() . "', 0, '" . $channel . "');");
		
		$conv = mysql_insert_id();
		
		// Insert the participants
		foreach ($participants AS $part)
		{
			$this->query("INSERT INTO participants (`user`,`conv`,`rights_set`) VALUES ('" . $part . "', '" . $conv . "', 1);");
			
		} // end foreach
		
		return $conv;
		
	} // end function
	
	public function exists($m, $participants, $channel)
	{
		// We can't have a conversation with less than 2 persons.
		if (count($participants) < 2)
			return false;
		
		// Get participants model
		$pM = $m->getModel('participants');
		
		// Set the args for 'caching'.
		$args = array($participants, $channel);
		
		// Select conversations that might have the 'thing'.
		$sConversations = $this->query("SELECT id FROM conversations WHERE isChannel = '" . $channel . "' AND persons = '" . count($participants) . "'") or $this->doAjaxError();
		
		// Go through them all
		while ($fConversation = $this->fetch($sConversations))
			if ($pM->hasParticipants($fConversation['id'], $participants))
			{
				// Cache the stuff for later use.
				$this->foundID   = $fConversation['id'];
				$this->foundArgs = $args;
				
				// Found
				return true;
				
			} // end if
		
		return false;
		
	} // end function
	
} // end class

$_ = 'modConversation';

?>